package cn.anecansaitin.whimsy.common.loot;

import cn.anecansaitin.whimsy.common.register.ModLootModifiers;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootPool;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.neoforged.neoforge.common.loot.IGlobalLootModifier;
import net.neoforged.neoforge.common.loot.LootModifier;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * 简单的通过LootPool来添加额外的战利品
 */
public class SimpleLootModifier extends LootModifier {
    public static final Codec<SimpleLootModifier> CODEC =
            RecordCodecBuilder.create(instance -> LootModifier.codecStart(instance)
                    .and(instance.group(LootPool.CODEC.listOf().fieldOf("pools").forGetter(m -> m.pools)).t1())
                    .apply(instance, SimpleLootModifier::new));
    private final List<LootPool> pools;

    public SimpleLootModifier(LootItemCondition[] conditionsIn, @NotNull List<LootPool> pools) {
        super(conditionsIn);
        this.pools = pools;
    }

    @Override
    protected @NotNull ObjectArrayList<ItemStack> doApply(ObjectArrayList<ItemStack> generatedLoot, LootContext context) {
        for (LootPool pool : pools) {
            pool.addRandomItems(generatedLoot::add, context);
        }

        return generatedLoot;
    }

    @Override
    public Codec<? extends IGlobalLootModifier> codec() {
        return ModLootModifiers.SIMPLE_LOOT_MODIFIER_CODEC.get();
    }
}
